<?php

/**
 * Controlador de BackOffice
 *
 */

class Zwei_Admin_Controller{
  var $layout;
  var $page;
  var $id;
  var $name;
  var $target;
  var $maxsize;

  /**
   * Constructor
   * @param $page
   * @param $id
   * @return unknown_type
   */
  
  function __construct($page,$id=array()){
    $this->layout=array();
    $this->page=$page;
    $this->id=$id;
    $this->requested_params="";
  }

  function setId($id){
  	$this->id=$id;
  }

  function getLayout(){
    $xml=new Zwei_Admin_XML();
    $xml->parse(COMPONENTS_ADMIN_PATH."/".$this->page.".xml");
    $this->layout=$xml->elements;
    $this->name=$this->layout[0]['NAME'];
    $this->target=$this->layout[0]['TARGET'];
    $count=count($this->layout);
    for($i=1; $i<$count; $i++){
	  	$this->layout[$i]["VISIBLE"]=$this->layout[$i]["VISIBLE"]=="true"?true : false;
	    $this->layout[$i]["EDIT"]=$this->layout[$i]["EDIT"]=="true"?true : false;
	    $this->layout[$i]["ADD"]=$this->layout[$i]["ADD"]=="true"?true : false;
	}
  }

  function getData($start=0,$limit=20,$search="",$sort="",$dir="ASC"){
  	$form=new Zwei_Utils_Form();
    $model=$this->layout[0]["TARGET"];
    $modelobj=new $model();
    $select=$modelobj->select();

    if($sort!="") $select->order("$sort $dir");
    if(empty($this->id)) $select->limit($limit, $start);

    //@TODO if(method_exists($modelobj,"setSearch"))$modelobj->setSearch($search);
    
    //Get request parameters for the data fields
    $count=count($this->layout);
    for($i=1; $i<$count; $i++){
    	$field=$this->layout[$i]["TARGET"];
    	if(isset($form->$field) && !is_array($form->$field) && $form->$field!==""){
    		$select->where($select->getAdapter()->quoteInto("$field ?", $form->$field));
    	}
    }

    $rows=$modelobj->fetchAll($select);
    
    foreach ($rows as $row){
	  for($i=1; $i<$count; $i++){
	  	  if(isset($row[$this->layout[$i]["TARGET"]]))
		  	$this->layout[$i]["VALUE"][]=$row[$this->layout[$i]["TARGET"]];
		  elseif (isset($this->layout[$i]["DEFAULT"]))$this->layout[$i]["VALUE"][]=$this->layout[$i]["DEFAULT"];
		  else $this->layout[$i]["VALUE"][]="";
	  }
	}
	$this->maxsize=$rows->count();
  }

  function getRequested_params(){ 
  	$form=new Zwei_Utils_Form();
  	$count=count($this->layout);
  	$params="";

    for($i=1; $i<$count; $i++){
    	$field=$this->layout[$i]["TARGET"];
    	if(isset($form->$field)){
    		if(is_array($form->$field)){
    			$params.="&$field=".urlencode($form->{$field}[0]);
    		}else{
    			$params.="&$field=".urlencode($form->$field);
    		}
    	}
    }

  	return $params; 
  }
}
?>